package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Strategy;
import cn.wolfcode.luowowo.domain.StrategyCatalog;
import cn.wolfcode.luowowo.query.StrategyCatalogQuery;
import cn.wolfcode.luowowo.repository.StrategyCatalogRepositoey;
import cn.wolfcode.luowowo.service.IStrategyCatalogService;
import cn.wolfcode.luowowo.service.IStrategyService;
import cn.wolfcode.luowowo.util.DBHelper;
import cn.wolfcode.luowowo.util.LogicException;
import cn.wolfcode.luowowo.vo.CatalogVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StrategyCatalogServiceImpl implements IStrategyCatalogService {

    @Autowired
    private StrategyCatalogRepositoey strategyCatalogRepositoey;
    @Autowired
    private DestinationServiceImpl destinationService;
    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private MongoTemplate template;
    private Pageable pageable;

    @Override
    public List<StrategyCatalog> list() {
        return strategyCatalogRepositoey.findAll();
    }

    @Override
    public StrategyCatalog selectOne(String id) {
        return strategyCatalogRepositoey.findById(id).orElse(null);
    }

    @Override
    public Page<StrategyCatalog> query(StrategyCatalogQuery qo) {
        //创建查询对象
        Query query = new Query();
        //页面显示集合
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template, StrategyCatalog.class, query, pageable);

    }

    @Override
    public void saveOrUpdate(StrategyCatalog strategyCatalog) {
        if(!StringUtils.hasLength(strategyCatalog.getName())){
            throw new LogicException("名字不能为空");
        }
        //通过destId查询目的地名字,将名字设置给攻略分类的目的地名字中,再进行更新操作
        String name = destinationService.selectOne(strategyCatalog.getDestId()).getName();
        strategyCatalog.setDestName(name);
        strategyCatalogRepositoey.save(strategyCatalog);
    }

    @Override
    public void delete(String id) {
        strategyCatalogRepositoey.deleteById(id);
    }

    @Override
    public List<CatalogVO> queryCatalogs() {
        //查询攻略分类中目的地名字和对象CatalogVO<里面是分类id和名字组成的map集合>的集合
        List<CatalogVO> list = new ArrayList<>();
        TypedAggregation<StrategyCatalog> agg = Aggregation.newAggregation(StrategyCatalog.class,
                Aggregation.group("destName").
                        push("name").as("names").
                        push("id").as("ids")
                );
        AggregationResults<Map> aggregate = template.aggregate(agg, Map.class);
        List<Map> datas = aggregate.getMappedResults();
        for (Map data:datas
             ) {
            CatalogVO vo = new CatalogVO();
            vo.setDestName(data.get("_id").toString());
            //空集合来装CatalogVO对象中的mapList
            List<Map<String ,Object>> l = new ArrayList<>();
            List<Object> ids = (List<Object>)data.get("ids");
            List<Object> names = (List<Object>)data.get("names");
            for (int i = 0; i < names.size(); i++) {
                Map<String, Object> vv = new HashMap<>();
                String name = names.get(i).toString();
                String id = ids.get(i).toString();
                vv.put("id", id);
                vv.put("name", name);
                l.add(vv);
            }
            vo.setMapList(l);
            list.add(vo);

        }
        return list;


        /*List<CatalogVO> list = new ArrayList<>();
        TypedAggregation<StrategyCatalog> agg = Aggregation.newAggregation(StrategyCatalog.class,
                Aggregation.group("destName").
                        push("name").as("names").
                        push("id").as("ids")
        );
        AggregationResults<Map> result = template.aggregate(agg,Map.class);
        List<Map> datas = result.getMappedResults();
        for (Map data : datas) {
            CatalogVO vo = new CatalogVO();

            vo.setDestName(data.get("_id").toString());

            List<Map<String, Object>> mm = new ArrayList<>();
            List<Object> names = (List<Object>) data.get("names");
            List<Object> ids = (List<Object>) data.get("ids");
            for (int i = 0;i < names.size(); i++) {
                Map<String, Object> vv = new HashMap<>();
                String name = names.get(i).toString();
                String id = ids.get(i).toString();
                vv.put("id", id);
                vv.put("name", name);
                mm.add(vv);
            }
            vo.setMapList(mm);
            list.add(vo);
        }
        System.out.println(list);
        return list;*/


    }

    /**
     * 通过目的地id查询对应的攻略分类集合,再通过分类id查询对应的攻略集合将其设置进之前查询到的攻略分类集合中
     * @param destId
     * @return
     */
    @Override
    public List<StrategyCatalog> queryByDestId(String destId) {
        List<StrategyCatalog> list =  strategyCatalogRepositoey.findByDestId(destId);
        for (StrategyCatalog catalog:list
             ) {
            List<Strategy> strategies = strategyService.selectByCatalogId(catalog.getId());
            catalog.setStrategies(strategies);
        }
        return list;
    }

}

